﻿using GN.Pay.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GN.Pay.Core.Values.Services;
using GN.Framework.Utils;
using GN.Framework.Extensions;
using Abp.UI;

namespace GN.Pay.Application.Service
{
    /// <summary>
    /// 聚合短信支付服务
    /// </summary>
    public class JuhePaySmsService : JuheService, IPaySmsService
    {
        /// <summary>
        /// 
        /// </summary>
        protected override string AppKeyName
        {
            get
            {
                return "JuheSmsAppKey";
            }
        }

        private const string ServiceUrl = "http://v.juhe.cn/sms/send";

        private async Task SendAsync(string templateId, string mobile, IDictionary<string, string> args)
        {
            var parameters = new Dictionary<string, string>();
            parameters["mobile"] = mobile;
            parameters.Add("tpl_id", templateId); //短信模板ID，请参考个人中心短信模板设置
            var tempTplValues = "";
            if (args.Count() > 0)
            {
                Dictionary<string, string> juHeTplValue = new Dictionary<string, string>();
                foreach (var arg in args)
                {
                    if (!string.IsNullOrWhiteSpace(arg.Value))
                    {
                        juHeTplValue.Add("#" + arg.Key + "#", arg.Value);
                    }
                }
                tempTplValues = System.Web.HttpUtility.UrlEncode(HttpUtils.RequestString(juHeTplValue, false));
            }
            parameters.Add("tpl_value", tempTplValues); //变量名和变量值对。如果你的变量名或者变量值中带有#&amp;=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，&lt;a href=&quot;http://www.juhe.cn/news/index/id/50&quot; target=&quot;_blank&quot;&gt;详细说明&gt;&lt;/a&gt;
            parameters.Add("key", this.AppKey);//你申请的key
            parameters.Add("dtype", "json"); //返回数据的格式,xml或json，默认json
            string result = await HttpUtils.PostStringAsync(ServiceUrl, parameters);
            Dictionary<string, object> resultDic = new Dictionary<string, object>(
                result.JsonToObject<Dictionary<string, object>>(true),
                StringComparer.InvariantCultureIgnoreCase);
            var error_code = GetDictionaryValueOrDefault(resultDic, "error_code", "").ToString();
            if (error_code.ToString() != "0")
            {
                throw new UserFriendlyException(GetDictionaryValueOrDefault(resultDic, "reason", "").ToString());
            }
        }

        private Dictionary<string, string> GetSmsParam(IShortcutBindSmsContent content)
        {
            var args = new Dictionary<string, string>();
            args["userName"] = content.RealName;
            if (!string.IsNullOrWhiteSpace(content.CheckCode))
            {
                args["checkCode"] = content.CheckCode;
            }
            if (!string.IsNullOrWhiteSpace(content.CardNo) && content.CardNo.Length > 4)
            {
                args["cardNo"] = content.CardNo.Substring(content.CardNo.Length - 4);
            }
            args["expireMinute"] = content.ExpireMinute.ToString();
            return args;
        }

        /// <summary>
        /// 绑定
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task ShortcutBind(IShortcutBindSmsContent content)
        {
            var args = GetSmsParam(content);
            await SendAsync(content.SmsTemplate, content.MobilePhone, args);
        }

        /// <summary>
        /// 绑定失败
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task ShortcutBindFail(IShortcutBindSmsContent content)
        {
            var args = GetSmsParam(content);
            await SendAsync(content.SmsTemplate, content.MobilePhone, args);
        }

        /// <summary>
        /// 支付提示
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task ShortcutPay(IShortcutPaySmsContent content)
        {
            var args = GetSmsParam(content);
            args["orderNo"] = content.OrderNo;
            args["payMoney"] = content.PayMoney.ToString("N2");
            await SendAsync(content.SmsTemplate, content.MobilePhone, args);
        }

        /// <summary>
        /// 支付失败
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task ShortcutPayFail(IShortcutPaySmsContent content)
        {
            var args = GetSmsParam(content);
            args["orderNo"] = content.OrderNo;
            args["payMoney"] = content.PayMoney.ToString("N2");
            await SendAsync(content.SmsTemplate, content.MobilePhone, args);
        }
    }
}
